// export {}
import React, { useRef, useContext, useState, useEffect } from "react";
import { Space, Table, Tag, Layout, Button, Input, Form, Switch, Radio} from "antd";
import { ClientContext } from "../App";
import type { RecordType } from "../types/Record";
import type { SizeType } from "antd/es/config-provider/SizeContext";
import { AudioOutlined } from '@ant-design/icons';
import type { ExpandableConfig, TableRowSelection } from 'antd/es/table/interface';
import type { RadioChangeEvent } from 'antd';
import type { ColumnsType, TableProps, TablePaginationConfig} from 'antd/es/table';
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
import moment from 'moment';


//scene: id => {color,name} mapping
const sceneMap  = new Map()

const { Search } = Input;

type TablePaginationPosition =
  | 'topLeft'
  | 'topCenter'
  | 'topRight'
  | 'bottomLeft'
  | 'bottomCenter'
  | 'bottomRight';

const columns: ColumnsType<RecordType> = [
  {
    title: "时间",
    dataIndex: "timestamp",
    key: "timestamp",
    sorter: (a, b) => a.timestamp - b.timestamp,
    sortDirections: ['descend', 'ascend'],
    render: (text) => moment(text).format('YYYY-MM-DD HH:mm:ss'), // 将时间戳转换为标准日期格式
  },
  {
    title: "Uuid",
    dataIndex: "id",
    key: "id",
  },
  {
    title: "姓名",
    dataIndex: "name",
    key: "name",
    render: (text) => <a>{text}</a>,
    sorter: (a, b) => a.name.length - b.name.length,
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: "人脸识别的场景",
    dataIndex: "scene",
    key: "scene",
    render: (text) => sceneMap.get(text), 
    filters: [
      {
        text: '西北工业大学小东门',
        value: '西北工业大学小东门',
      },
      {
        text: '电子信息学院1楼大门',
        value: '电子信息学院1楼大门',
      },
      {
        text: '云天苑E座1楼大门',
        value: '云天苑E座1楼大门',
      },
      {
        text: '云天苑F座1楼大门',
        value: '云天苑F座1楼大门',
      },
    ],
    onFilter: (value, record) => record.scene.indexOf(value as string) === 0,
  },
  {
    title: "是否通过",
    dataIndex: "pass",
    key: "pass",
    filters: [
      {
        text: '1',
        value: 1,
      },
      {
        text: '0',
        value: 0,
      },
    ],
    onFilter: (value, record) => record.pass === 0,
  },
  {
    title: "识别时间（ms）",
    dataIndex: "infer-time",
    key: "infer-time",
    sorter: (a, b) => a["infer-time"] - b["infer-time"],
    sortDirections: ['descend', 'ascend'],
  },
  {
    title: "识别正确率",
    dataIndex: "acc",
    key: "acc",
    sorter: (a, b) => a.acc - b.acc,
    sortDirections: ['descend', 'ascend'],
  },
];
const formItemLayout = {
  labelCol: { span: 200 },
  wrapperCol: { span: 100 },
};

const defaultExpandable = { 
  expandedRowRender: 
    // (record: any) => <p>{record.info["detail"]}</p>
    (record: any) =>{
      const keys: string[] = []
      const values: any[] = []
      keys.push("key")
      values.push(record.info["key"])
      Object.entries(record.info.detail).forEach(([k, v]) => {
        keys.push(k)
        values.push(v)
      });
      keys.push("privilege") 
      let scenes : string =  ''
      Object.entries(record.info.privilege).forEach(([k, v]) => {
        let scene = sceneMap.get(v)
        scenes = `${scenes}   ${scene}`
      });
      values.push(scenes)
      return(       
        <Layout>
        <Form {...formItemLayout} layout="inline">
        {
          keys.map((k,i)=>{
            return (<Form.Item label={k}>
              {values[i]}
            </Form.Item >)
          })
        }  
        </Form>
        </Layout>
      )
  } 
};

const suffix = (
  <AudioOutlined
    style={{
      fontSize: 16,
      color: '#1677ff',
    }}
  />
);

let allReocrds: React.SetStateAction<never[]> = []

const Record: React.FC = () => {
  const [size] = useState<SizeType>('large');
  const [expandable] = useState<ExpandableConfig<RecordType> | undefined>(
    defaultExpandable,
  );
  const [rowSelection] = useState<TableRowSelection<RecordType> | undefined>({});
  const [hasData] = useState(true);
  const [tableLayout] = useState();
  const [top] = useState<TablePaginationPosition | 'none'>('none');
  const [bottom] = useState<TablePaginationPosition>('bottomRight');
  const [ellipsis] = useState(false);
  const [yScroll] = useState(false);
  const [xScroll] = useState<string>();

  const scroll: { x?: number | string; y?: number | string } = {};
  if (yScroll) {
    scroll.y = 240;
  }
  if (xScroll) {
    scroll.x = '100vw';
  }

  const tableColumns = columns.map((item) => ({ ...item, ellipsis }));
  if (xScroll === 'fixed') {
    tableColumns[0].fixed = true;
    tableColumns[tableColumns.length - 1].fixed = 'right';
  }

  const tableProps: TableProps<RecordType> = {
    size,
    expandable,
    rowSelection,
    scroll,
    tableLayout,
  };
  const { client, theme } = useContext(ClientContext);

  const [record, setRecord] = useState([]);



  console.log(client.getToken());

  const search=(e:any)=>{

    if (e == ""){     
      setRecord(allReocrds);
    }
    else{  
      const searchList: React.SetStateAction<never[]> = []
      record.find((value)=>{
        const {name} = value
      
        if (name==e)
        {
          searchList.push(value)
        }
        
      })

      setRecord(searchList);
    }
        
  }

  // 获取所有场景信息
  useEffect(() => {
    async function getScene() {
      const { message, code, data } = await (await client.get("/get/scene"))
        .data;

      if (code == 0) {
        data.scenes.map(({ id, name }: any) => {
          sceneMap.set(id, name);
        });
      }
      // console.log(sceneMap);
    }
    getScene();
  }, []);

  useEffect(() => {
    async function getRecord() {
      const {message, code, data} = await (
        await client.post("/post/record", {token: client.getToken(), number: 0})
      ).data;

      // 成功
      if (code == 0) {
        setRecord(data.records);
        // save all records use deep copy
        allReocrds = data.records
      }
    }
    getRecord();
  }, []);

  console.log(record);
  return (
    <Layout>
          <Search 
          placeholder="input search text" 
          allowClear 
          onSearch={search} 
          style={{paddingLeft:"10rem",width:"70rem"}} />
      <div style={{paddingBottom:"3rem"}}/>
      <Table
        {...tableProps}
        pagination={{ position: [top as TablePaginationPosition, bottom] }}
        columns={tableColumns}
        rowKey={(record) => record.id}
        dataSource={hasData ? record as RecordType[] : []}
        scroll={scroll}
      />
    </Layout>
  )
};

export default Record;
